<template>
    <div class="page-container">
        <div class="card">
            <div style="font-size: 16px;">
                个人中心
            </div>
            <el-form ref="personRef" :rules="userRules" :model="userinfo" label-width="80"
                style="padding: 20px 30px 10px 0;">
                <el-form-item prop="username" label="账号">
                    <el-input v-model="userinfo.username" autocomplete="off" disabled />
                </el-form-item>
                <el-form-item prop="nickname" label="名称">
                    <el-input v-model="userinfo.nickname" autocomplete="off" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item prop="phone" label="电话">
                    <el-input v-model="userinfo.phone" autocomplete="off" placeholder="请输入电话" />
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                    <el-input v-model="userinfo.email" autocomplete="off" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item prop="avatar" label="头像">
                    <el-upload :action="getConfig('API_BASE_URL').replace(/\/?$/, '/') + 'files/upload'"
                        :on-success="handleFileSuccess" :headers="{ token: tokenStore.token }" :show-file-list="false"
                        list-type="picture" :before-upload="beforeUpload">
                        <el-image v-if="userinfo.avatar" :src="userinfo.avatar" class="littlePic" />
                        <el-button v-else type="primary">点击上传头像</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div style="text-align: center;">
                <el-button type="primary" @click="update" style="padding: 10px 50px;">
                    保存
                </el-button>
            </div>
        </div>
        <div class="card" style="margin-top: 10px;">
            <div style="font-size: 16px;">
                修改密码
            </div>
            <div style="padding: 20px 30px 10px 30px;">
                <el-form status-icon ref="passwordRef" :model="changePassword" :rules="passwordRules">
                    <el-form-item prop="oldPassword">
                        <el-input show-password v-model="changePassword.oldPassword" autocomplete="off"
                            prefix-icon="Lock" placeholder="请输入原密码" />
                    </el-form-item>
                    <el-form-item prop="newPassword">
                        <el-input show-password v-model="changePassword.newPassword" autocomplete="off"
                            prefix-icon="Lock" placeholder="请输入新密码" />
                    </el-form-item>
                    <el-form-item prop="confirmPassword">
                        <el-input show-password v-model="changePassword.confirmPassword" autocomplete="off"
                            prefix-icon="Lock" placeholder="请确认新密码" />
                    </el-form-item>
                </el-form>
                <div style="text-align: center;">
                    <el-button type="primary" @click="updatePassword" style="padding: 10px 50px;">
                        保存密码
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { getConfig } from '@/utils/config';
import router from '@/router';
import { beforeUpload } from '@/utils/function';
import { useUserStore } from '@/store/user';
import { useTokenStore } from '@/store/token';
import { userInfoUpdateAvatarService, userInfoUpdatePasswordService, userInfoUpdateService } from '@/api/user';

const userStore = useUserStore()
const tokenStore = useTokenStore()
const personRef = ref()
const passwordRef = ref()

// 解构？？
const userinfo = ref({...userStore.getUser()})

const userRules = ref({
    nickname: [
        { required: true, message: '请填写昵称', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请填写电话', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请填写邮箱', trigger: 'blur' },
    ]
})

const changePassword = ref({
    oldPassword:'',
    newPassword:'',
    confirmPassword:''
})

const validatePass = (rule, value, callback) => {
    if (value !== changePassword.value.newPassword) {
        callback(new Error("两次密码填写不一致!"))
    } else {
        callback()
    }
}

const passwordRules = ref({
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' }
    ]
})
const update = (res) => {
    // personRef是表单的引用
    personRef.value.validate(async(valid) => {
        if (valid) { //说明是表单验证通过的情况下
            const result = await userInfoUpdateService(userinfo.value)
            ElMessage.success("更新成功")
            userStore.setUser(userinfo.value)
        }
    })
}


const handleFileSuccess = async(res) => {
    if (res.code === '200') {
        await userInfoUpdateAvatarService(res.data)
        ElMessage.success("头像上传成功")
        userinfo.value.avatar = res.data
        userStore.setUserAvatar(res.data)
    } else {
        ElMessage({
            showClose: true,
            message: res.msg,
            type: 'warning',
            duration: 0,
        })
    }
}


const updatePassword = () => {
    passwordRef.value.validate(async(valid) => {
        if (true) { //说明是表单验证通过的情况下
            const result = await userInfoUpdatePasswordService(changePassword.value)
            ElMessage.success("修改密码成功,请重新登录")
            userStore.$reset
            router.push('/login')
        }
    })
}
</script>